<template>
  <div class="users">
    <!-- 目录导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区域 -->
    <el-card>
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input placeholder="请输入内容" v-model="queryInfo.query" @input="getUserList">
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button size="medium" type="primary" icon="el-icon-plus" @click="openUserDialog('add')">添加用户</el-button>
        </el-col>
      </el-row>
      <!-- 表格主体区域 -->
      <el-table :data="userList" border stripe>
        <el-table-column type="index"></el-table-column>
        <el-table-column prop="username" label="用户名"></el-table-column>
        <el-table-column prop="email" label="邮箱"></el-table-column>
        <el-table-column prop="mobile" label="电话"></el-table-column>
        <el-table-column prop="role_name" label="角色名称"></el-table-column>
        <el-table-column label="状态">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.mg_state" @change="changeUserState(scope.row)"></el-switch>
          </template>
        </el-table-column>
        <el-table-column prop="operation" label="操作" width="180">
          <template slot-scope="scope">
            <el-button type="primary" size="small" icon="el-icon-edit" @click="openUserDialog('edit', scope.row)"></el-button>
            <el-button type="danger" size="small" icon="el-icon-delete" @click="delConfirmMsg(scope.row)"></el-button>
            <el-tooltip effect="dark" content="分配权限" placement="top" :enterable="false">
              <el-button type="warning" size="small" icon="el-icon-setting" @click="openUserDialog('setRight', scope.row)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[2, 5, 10]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
    </el-card>
    <!-- 添加用户的对话框 -->
    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      width="50%" @close="dialogClose">
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" v-if="addFormConfig.isForm">
        <el-form-item prop="username">
          <el-input prefix-icon="el-icon-user" v-model="addForm.username"
            placeholder="请输入用户名" :disabled="addFormConfig.username.isDisabled">
          </el-input>
        </el-form-item>
        <el-form-item prop="password" v-if="addFormConfig.password.isShow">
          <el-input prefix-icon="el-icon-lock" type="password" v-model="addForm.password" placeholder="请输入密码"></el-input>
        </el-form-item>
        <el-form-item prop="email">
          <el-input prefix-icon="el-icon-receiving" v-model="addForm.email" placeholder="请输入邮箱"></el-input>
        </el-form-item>
        <el-form-item prop="mobile">
          <el-input prefix-icon="el-icon-mobile-phone" v-model="addForm.mobile" placeholder="请输入手机"></el-input>
        </el-form-item>
      </el-form>
      <div v-else>
        <p>当前用户：{{currentUserInfo.username}}</p>
        <p>角色名称：{{currentUserInfo.role_name}}</p>
        <p>分配角色：
          <el-select v-model="selectRoleId" placeholder="请选择" size="medium">
            <el-option
              v-for="item in rolesList"
              :key="item.id"
              :label="item.roleName"
              :value="item.id">
            </el-option>
          </el-select>
        </p>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFormData(addFormConfig.option)" size="medium">确定</el-button>
        <el-button size="medium" type="danger" @click="resetFormData">重置</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    // 自定义的邮箱验证规则
    var checkEmail = (rule, value, callback) => {
      const regEmail = /^([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$/;
      if (regEmail.test(value)) {
        return callback()
      }
      callback('请输入合法邮箱')
    }
    // 自定义的手机号验证规则
    var checkMobile = (rule, value, callback) => {
      const regMobile = /^((13[0-9])|(17[0-1,6-8])|(15[^4,\\D])|(18[0-9]))\d{8}$/;
      if (regMobile.test(value)) {
        return callback()
      }
      callback('请输入合法的手机号')
    }
    return {
      // 用户数据列表查询参数
      queryInfo: {
        query: '',
        pagenum: 1,
        pagesize: 2
      },
      // 用户列表
      userList: [],
      total: 0,
      // 控制对话框的显示和隐藏
      dialogVisible: false,
      // 控制对话框标题
      dialogTitle: '',
      // 添加用户的表单数据
      addForm: {
        id: 0,
        username: '',
        password: '',
        email: '',
        mobile: '',
      },
      // 添加用户的表单验证规则
      addFormRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 4, max: 20, message: '长度在 4 到 20 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      },
      // 控制表单内部item的显示和隐藏
      addFormConfig: {
        option: 'add',//当前表单操作
        isForm: true,
        username: {
          isDisabled: false,
          isShow: true
        },
        password: {
          isDisabled: false,
          isShow: true
        }
      },
      // 存放用户角色列表
      rolesList: [],
      // 当前用户信息
      currentUserInfo: {},
      // 已选中的角色id
      selectRoleId: ''
    }
  },
  created(){
    this.getUserList()
  },
  methods: {
    // 获取用户列表
    async getUserList() {
      const {data: res} = await this.$axios.get('users', {params: this.queryInfo})
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.userList = res.data.users
      this.total = res.data.total
    },
    // 改变用户状态
    async changeUserState(userInfo) {
      const {data: res} = await this.$axios.put(`users/${userInfo.id}/state/${userInfo.mg_state}`)
      if (res.meta.status !== 200) {
        userInfo.mg_state = !userInfo.mg_state
        return this.$message.error(res.meta.msg)
      }
      this.$message({message: res.meta.msg, type: 'success'})
    },
    // 监听pagesize的改变事件
    handleSizeChange(newSize) {
      console.log(`每页 ${newSize} 条`)
      this.queryInfo.pagesize = newSize
      this.getUserList()
    },
    // 监听页码值的改变
    handleCurrentChange(newPage) {
      console.log(`当前页: ${newPage}`)
      this.queryInfo.pagenum = newPage
      this.getUserList()
    },
    // 打开用户对话框
    openUserDialog(option, data) {
      this.dialogVisible = !this.dialogVisible
      this.addFormConfig.option = option
      switch (option) {
        case 'add':
          this.dialogTitle = '添加用户信息'
          this.addFormConfig.isForm = true
          break;
        case 'edit':
          console.log(data);
          this.dialogTitle = '编辑用户信息'
          this.addFormConfig.isForm = true
          this.addFormConfig.username.isDisabled = true
          this.addFormConfig.password.isShow = false
          // const {username,email,mobile} = data
          // this.addForm = data
          this.addForm.id = data.id
          this.addForm.username = data.username
          this.addForm.email = data.email
          this.addForm.mobile = data.mobile
          break;
        case 'setRight':
          this.dialogTitle = '分配用户权限'
          this.addFormConfig.isForm = false
          this.currentUserInfo = data
          this.getRolesList()
          break;
      }
    },
    // 监听对话框关闭事件
    dialogClose() {
      this.addFormConfig.username.isDisabled = false
      this.addFormConfig.password.isShow = true
      this.addForm.username = ''
      this.addForm.email = ''
      this.addForm.mobile = ''
      if (this.addFormConfig.isForm) {
        this.$refs.addFormRef.resetFields()
      }
    },
    // 提交表单数据
    submitFormData(option) {
      console.log('option: '+option);
      switch (option) {
        case 'add':
          this.$refs.addFormRef.validate(async valid => {
            if (!valid) return
            const { data: res } = await this.$axios.post('users', this.addForm)
            if (res.meta.status !== 201) {
              this.$message.error(res.meta.msg)
            } else {
              this.$message({message: res.meta.msg, type: 'success'})
              this.getUserList()
              this.dialogVisible = !this.dialogVisible
            }
          })
          break;
        case 'edit':
          this.$refs.addFormRef.validate(async valid => {
            if (!valid) return
            const { data: resEdit } = await this.$axios.put(`users/${this.addForm.id}`, this.addForm)
            if (resEdit.meta.status !== 200) {
              this.$message.error(resEdit.meta.msg)
            } else {
              this.$message({message: resEdit.meta.msg, type: 'success'})
              this.getUserList()
              this.dialogVisible = !this.dialogVisible
            }
          })
          break;
        case 'setRight':
          console.log('发送修改用户权限数据的请求');
          if (!this.selectRoleId) {
            return this.$message.error('请选择要分配的角色!')
          }
          this.$axios.put(
            `users/${this.currentUserInfo.id}/role`,
            {rid: this.selectRoleId}
          ).then(res => {
            
            if (res.data.meta.status !== 200) {
              this.$message.error(res.data.meta.msg)
            } else {
              this.$message({message: res.data.meta.msg, type: 'success'})
              this.getUserList()
              this.dialogVisible = !this.dialogVisible
            }
          })
          break;
      }
      /* this.$refs.addFormRef.validate(async valid => {
        console.log(valid);
        if (!valid) return
        // 发送登录请求
        switch (option) {
          case 'add':
            const { data: res } = await this.$axios.post('users', this.addForm)
            if (res.meta.status !== 201) {
              this.$message.error(res.meta.msg)
            } else {
              this.$message({message: res.meta.msg, type: 'success'})
              this.getUserList()
              this.dialogVisible = !this.dialogVisible
            }
            break;
          case 'edit':
            const { data: resEdit } = await this.$axios.put(`users/${this.addForm.id}`, this.addForm)
            if (resEdit.meta.status !== 200) {
              this.$message.error(resEdit.meta.msg)
            } else {
              this.$message({message: resEdit.meta.msg, type: 'success'})
              this.getUserList()
              this.dialogVisible = !this.dialogVisible
            }
            break;
          case 'setRight':
            console.log('发送修改用户权限数据的请求');
            break;
        }
      }) */
      
    },
    // 重置表单数据
    resetFormData() {
      this.$refs.addFormRef.resetFields()
    },
    // 打开删除确认框
    delConfirmMsg(userInfo) {
      this.$confirm('此操作将删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const { data: res } = await this.$axios.delete(`users/${userInfo.id}`)
        //console.log(res)
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
        this.$message({type: 'success', message: res.meta.msg})
        this.getUserList()
      }).catch(() => {
        this.$message({type: 'info', message: '已取消删除'})   
      })
    },
    // 获取用户角色列表
    async getRolesList() {
      const {data: res} = await this.$axios.get('roles')
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.rolesList = res.data
      console.log(res);
    },
    // 定义统一数据请求
    async setRoleInfo() {}
  },
}
</script>

<style lang="less" scoped>

</style>